#include <unistd.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "fd_context.h"
#include "hook_interface.h"

CoFdContext::CoFdContext(int fd, CoFdType type)
{
    _fd = fd; 
    _type = type;
    _is_block = true;
	_events = 0;
}

CoFdContext::~CoFdContext()
{
    if (_fd >= 0) {
        close_f(_fd);
        _fd = -1;
    }
}

int CoFdContext::get_fd()
{
    return _fd; 
}

CoFdType CoFdContext::get_type()
{
    return _type;
}

bool CoFdContext::is_block()
{
    return _is_block;
}

void CoFdContext::set_block_flag(bool block)
{
    _is_block = block;
}

void CoFdContext::set_timeout(CoFdTimeoutType type, int msec)
{
    _timeouts[type] = msec; 
}

int CoFdContext::get_timeout(CoFdTimeoutType type)
{
    auto iter = _timeouts.find(type); 
    return iter != _timeouts.end() ? iter->second : -1;
}

CoFdContextPtr CoFdContext::clone(int fd)
{
    CoFdContextPtr ctx(new CoFdContext(fd, _type));
    ctx->_is_block = _is_block;
    ctx->_timeouts = _timeouts;
    return ctx;
}

void CoFdContext::set_events(int events)
{
    _events = events; 
}

int CoFdContext::get_events()
{
    return _events;
}

void CoFdContext::reset_events()
{
    _events = 0; 
}

CoSocketContext::CoSocketContext( int fd, CoFdType type, CoSocketAttribute attr) : CoFdContext(fd, type)
{
    _attr = attr; 
}

CoFdContextPtr CoSocketContext::clone(int fd)
{
    CoFdContextPtr ctx(new CoSocketContext(fd, _type, _attr));
    ctx->_is_block = _is_block;
    ctx->_timeouts = _timeouts;
    return ctx;
}

CoSocketAttribute CoSocketContext::get_attr()
{
    return _attr;
}

